<template>
    <view class="container">
        <!-- 设置图标 -->
        <view class="settings-icon">
            <image src="/static/icon/设置.png" class="icon-settings"></image>
        </view>

        <!-- 用户信息卡片 -->
        <view class="user-card">
            <view class="user-card-content">
                <!-- 头像和用户基本信息 -->
                <view class="user-header">
                    <view class="avatar-container">
                        <image class="avatar" :src="userInfo.avatar || '/static/icon/头像.png'"></image>
                    </view>
                    <view class="user-info">
                        <view class="name-row">
                            <text class="user-name">{{ userInfo.nickname || '未登录' }}</text>
                            <text class="user-id" v-if="userInfo.id">ID: {{ userInfo.id }}</text>
                        </view>
                    </view>
                </view>

                <!-- 用户数据统计 -->
                <view class="user-stats">
                    <view class="stat-item" @click="goToBalance">
                        <text class="stat-value">{{ userInfo.balance || '0.00' }}</text>
                        <text class="stat-label">余额</text>
                    </view>
                    <view class="stat-item" @click="goToBalance">
                        <text class="stat-value">{{ userInfo.points || '0.00' }}</text>
                        <text class="stat-label">积分</text>
                    </view>
                    <view class="stat-item" @click="goToCoupon">
                        <text class="stat-value">{{ couponCount }}</text>
                        <text class="stat-label">优惠券</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 常用工具区 -->
        <view class="tools-section">
            <view class="section-header">
                <text class="section-title">常用工具</text>
            </view>
            <view class="tools-grid">
                <view class="tool-item" @click="goToCouponCenter">
                    <view class="tool-icon-wrapper">
                        <image src="/static/icon/领券中心.png" class="tool-icon"></image>
                    </view>
                    <text class="tool-name">领券中心</text>
                </view>
                <view class="tool-item" @click="goToCoupon">
                    <view class="tool-icon-wrapper">
                        <image src="/static/icon/我的优惠券.png" class="tool-icon"></image>
                    </view>
                    <text class="tool-name">我的优惠券</text>
                </view>
                <view class="tool-item" @click="goToBalance">
                    <view class="tool-icon-wrapper">
                        <image src="/static/icon/余额明细.png" class="tool-icon"></image>
                    </view>
                    <text class="tool-name">余额明细</text>
                </view>
                <view class="tool-item" @click="goToAccountBind">
                    <view class="tool-icon-wrapper">
                        <image src="/static/icon/wechat.png" class="tool-icon"></image>
                    </view>
                    <text class="tool-name">账号绑定</text>
                </view>
                <view class="tool-item" @click="goToPhone">
                    <view class="tool-icon-wrapper">
                        <image src="/static/icon/电话.png" class="tool-icon"></image>
                    </view>
                    <text class="tool-name">联系我们</text>
                </view>
            </view>
        </view>

        <!-- 退出登录按钮 -->
        <view class="logout-section">
            <button class="logout-btn" @click="handleLogout">退出登录</button>
        </view>

        <!-- 底部导航栏 -->
        <tab-bar active="user"></tab-bar>
    </view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import TabBar from '@/components/tabBar/TabBar.vue';
import request from '@/utils/request.js';
import { getUserInfo, logout } from '@/utils/auth.js';
import api from '@/utils/api.js';
// 用户信息
const userInfo = ref({});
const couponCount = ref(0);

// 初始化数据
onMounted(() => {
    // 监听全局tab切换事件
    uni.$on('tabChange', handleGlobalTabChange);
    
    // 获取用户信息
    loadUserInfo();
    
    // 获取优惠券数量
    loadCouponCount();
});

// 获取用户信息
const loadUserInfo = () => {
    // 从本地存储获取用户信息
    const localUserInfo = getUserInfo();
    if (localUserInfo) {
        userInfo.value = localUserInfo;
    }
    
    // 从服务器获取最新用户信息
    request.get('/api/mobile/user/profile')
        .then(res => {
            if (res.code === 200) {
                userInfo.value = res.data;
            }
        })
        .catch(err => {
            console.log('获取用户信息失败', err);
        });
};

// 获取优惠券数量
const loadCouponCount = async () => {
    try {
        const response = await api.coupon.getUserCoupons(); // 使用await等待异步操作
        if (response && response.success) { // 确保response存在且包含success字段
            let res = response.data;
            //遍历
            for (let i = 0; i < res.length; i++) {
                if(res[i].status === 1) { //未使用
                    couponCount.value++; // 增加未使用的数量
                } 
            }
            console.log("返回用户优惠卷数据", couponCount.value);
        }
    } catch (error) {
        console.error('获取用户优惠券列表失败:', error);
    }
};

// 处理全局tab切换事件
const handleGlobalTabChange = (tab) => {
    if (tab === 'user') return; // 当前已经是用户页，不需要处理

    const routes = {
        'home': '/pages/index/index',
        'coupon': '/pages/coupon/coupon',
        'order': '/pages/order/order'
    };

    const url = routes[tab];
    if (!url) return;

    // 尝试使用redirectTo，这对非tabBar页面有效
    uni.redirectTo({
        url,
        fail: () => {
            // 如果失败则尝试强制刷新到新页面
            if (typeof window !== 'undefined') {
                window.location.replace('#' + url);
            }
        }
    });
};

// 组件销毁前移除事件监听
onBeforeUnmount(() => {
    uni.$off('tabChange', handleGlobalTabChange);
});

// 跳转到余额明细
const goToBalance = () => {
    uni.navigateTo({
        url: '/pages/balance/balance'
    });
};

// 跳转到我的优惠券
const goToCoupon = () => {
    uni.navigateTo({
        url: '/pages/mycoupon/mycoupon'
    });
};

// 跳转到领券中心
const goToCouponCenter = () => {
    uni.switchTab({
        url: '/pages/coupon/coupon'
    });
};

// 跳转到订单页面
const goToOrder = (status = '') => {
    // 由于已移除订单模块，此方法保留但不再使用
    console.log('订单模块已移除');
};

// 跳转到账号绑定
const goToAccountBind = () => {
    uni.navigateTo({
        url: '/pages/accountBind/accountBind'
    });
};

// 跳转到联系我们
const goToPhone = () => {
    uni.navigateTo({
        url: '/pages/phone/phone'
    });
};

// 处理退出登录
const handleLogout = () => {
    uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                // 清除登录状态
                logout();
                
                // 清除所有缓存数据
                try {
                    uni.clearStorageSync();
                    console.log('清除所有缓存数据成功');
                } catch (e) {
                    console.error('清除缓存失败', e);
                }
                
                // 显示提示
                uni.showToast({
                    title: '已退出登录',
                    icon: 'success'
                });
                
                // 跳转到登录页面
                setTimeout(() => {
                    uni.reLaunch({
                        url: '/pages/login/login'
                    });
                }, 1500);
            }
        }
    });
};
</script>

<style>
page {
    background: linear-gradient(to bottom, #7FB992 200rpx, #f8f8f8 400rpx);
    min-height: 100%;
}

.container {
    padding-bottom: 100rpx;
    min-height: 100vh;
}

/* 设置图标 */
.settings-icon {
    position: absolute;
    top: 180rpx;
    /* 调整位置与原型图一致 */
    right: 30rpx;
    z-index: 99;
}

.icon-settings {
    width: 50rpx;
    height: 50rpx;
}

/* 用户卡片样式 */
.user-card {
    margin: 30rpx;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
    overflow: hidden;
    position: relative;
    z-index: 2;
}

.user-card-content {
    padding: 30rpx;
}

/* 头像和用户信息行 */
.user-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
}

/* 头像容器 */
.avatar-container {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    border: 1rpx solid #EEEEEE;
    overflow: hidden;
}

.avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50rpx;
}

/* 用户基本信息 */
.user-info {
    flex: 1;
}

.name-row {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
}

.user-id {
    font-size: 24rpx;
    color: #999999;
    margin-top: 10rpx;
}

/* 用户数据统计 */
.user-stats {
    display: flex;
    justify-content: space-between;
    border-top: 1rpx solid #EEEEEE;
    padding-top: 30rpx;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
}

.stat-value {
    font-size: 40rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 10rpx;
}

.stat-label {
    font-size: 28rpx;
    color: #999999;
}

/* 工具区域 */
.tools-section {
    margin: 30rpx;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
}

.view-all {
    display: flex;
    align-items: center;
}

.view-all-text {
    font-size: 28rpx;
    color: #999999;
}

.view-all-icon {
    font-size: 28rpx;
    color: #999999;
    margin-left: 4rpx;
}

.tools-grid {
    display: flex;
    flex-wrap: wrap;
}

.tool-item {
    width: 33.33%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20rpx;
}

.tool-icon-wrapper {
    width: 110rpx;
    height: 110rpx;
    border-radius: 55rpx;
    background-color: #f8f8f8;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15rpx;
}

.tool-icon {
    width: 55rpx;
    height: 55rpx;
}

.tool-name {
    font-size: 24rpx;
    color: #666666;
}

/* 退出登录按钮 */
.logout-section {
    margin: 50rpx 30rpx 30rpx;
}

.logout-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    background-color: #FFFFFF;
    color: #FF6B6B;
    border-radius: 16rpx;
    font-size: 32rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
}
</style>
